
import subprocess
import json
import os


def curl_request(method, url, data=None, headers=None):
    cmd = ['curl', '-s', '-X', method.upper(), url]

    if headers:
        for k, v in headers.items():
            cmd.extend(['-H', f'{k}: {v}'])

    if data and method.upper() in ['POST', 'PUT']:
        cmd.extend(['-d', json.dumps(data)])

    # 打印可以在Linux终端直接运行的curl命令
    print("Linux可执行curl命令:")
    curl_cmd_parts = ["curl", "-s", "-X", method.upper(), url]
    if headers:
        for k, v in headers.items():
            curl_cmd_parts.extend(['-H', f'{k}: {v}'])
    if data and method.upper() in ['POST', 'PUT']:
        curl_cmd_parts.extend(['-d', json.dumps(data, ensure_ascii=False)])

    # 构建可以直接在Linux终端运行的命令字符串
    curl_cmd_str = " ".join([f"'{part}'" if " " in part or ":" in part else part for part in curl_cmd_parts])
    print(curl_cmd_str)

    # cmd.extend(['-v'])  # 启用详细输出
    try:
        result = subprocess.run(cmd,
                                capture_output=True,
                                text=True,
                                check=True)
        print("返回码:", result)
        print("cURL请求成功: ", result.stdout)
        return json.loads(result.stdout)
    except subprocess.CalledProcessError as e:
        print(f"cURL请求失败: {e.stderr}")
        return {"ErrCode": 1000, "ErrMsg": "cURL请求失败: {e.stderr}"}
    except json.JSONDecodeError:
        # return result.stdout
        return {"ErrCode": 1001, "ErrMsg": result.stdout}


def curl_request_bak(method, url, data=None, headers=None):
    cmd = ['curl', '-s', '-X', method.upper(), url]
    
    if headers:
        for k, v in headers.items():
            cmd.extend(['-H', f'{k}: {v}'])
    
    if data and method.upper() in ['POST', 'PUT']:
        cmd.extend(['-d', json.dumps(data)])
    # cmd.extend(['-v'])  # 启用详细输出
    try:
        result = subprocess.run(cmd, 
                              capture_output=True, 
                              text=True,
                              check=True)
        print("返回码:", result.returncode)
        print("cURL请求成功: ",result.stdout)
        return json.loads(result.stdout)
    except subprocess.CalledProcessError as e:
        print(f"cURL请求失败: {e.stderr}")
        return {"ErrCode":1000,"ErrMsg":"cURL请求失败: {e.stderr}"}
    except json.JSONDecodeError:
        # return result.stdout
        return {"ErrCode":1001,"ErrMsg":result.stdout}


def curl_request_file(method, url, local_image_file=None, headers=None):
    local_image_file = local_image_file.replace('\\', '/')
    if not os.path.exists(local_image_file):
        return {"ErrCode": 1002, "ErrMsg": "文件不存在"}
    if 'Content-Type' in headers:
        del headers['Content-Type']
    # 构建curl命令
    cmd = [
        'curl', '-s', '-F', f'image=@{local_image_file}', '-X', method.upper(), url
    ]
    if headers:
        for k, v in headers.items():
            cmd.extend(['-H', f'{k}: {v}'])
    print("cmd",cmd)
    # 执行curl命令并获取响应
    try:
        response = subprocess.run(cmd, capture_output=True, text=True, check=True)
        print('响应内容:', response)
        return json.loads(response.stdout)
    except subprocess.CalledProcessError as e:
        print('上传失败:', e)
        return {"ErrCode":1000,"ErrMsg":"cURL请求失败: {e.stderr}"}
    except json.JSONDecodeError:
        # return result.stdout
        return {"ErrCode":1001,"ErrMsg":response.stdout}



